package com.sooncode.project.focusservice._.infrastructure.file;

import com.mongodb.client.gridfs.model.GridFSFile;
import com.sooncode.project.springcloudcommon.exception.BaseException;
import org.apache.poi.util.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


/**
 * 类名: StoreFile
 * 说明: TODO
 * 创建日期: 2021-11-24 11:54
 * 创建人: 赵金歌
 **/
@Component
public class StoreFile implements IStoreFile {
    @Autowired
    GridFsTemplate gridFsTemplate;

    @Override
    public void SaveFile(String id, InputStream file){
        gridFsTemplate.store(file,id);
    }
    @Override
    public void DeleteFile(String id){
        gridFsTemplate.delete(new Query(Criteria.where("filename").is(id)));
    }
    @Override
    public void GetFileStream(String id, OutputStream outputStream) throws IOException {
        GridFSFile gridFSFile = gridFsTemplate.findOne(new Query(Criteria.where("filename").is(id)));
        if(gridFSFile==null) return;
        GridFsResource resource = gridFsTemplate.getResource(gridFSFile);
        IOUtils.copy(resource.getInputStream(),outputStream);
    }

}
